<?php

namespace app\api\controller;

use app\api\model\Follow as ModelFollow;
use app\api\model\User;
use app\common\LogService;

class Follow extends Base
{
    // 我的 | Ta 的关注
    public function index($id = 0)
    {
        if ($id != 0) {
            $exist = User::find($id);
            if (!$exist) return error('用户不存在');
        } else {
            $id = $this->uid;
        }
        $list = ModelFollow::getMyFollows($id);
        LogService::record(
            user_id: getUid(),
            name: '查看关注',
            target_id: $id
        );
        return success($list);
    }
    // 我的 | Ta的粉丝
    public function list($id = 0)
    {
        if ($id != 0) {
            $exist = User::find($id);
            if (!$exist) return error('用户不存在');
        } else {
            $id = $this->uid;
        }
        $list = ModelFollow::with(['userInfo' => function ($query) {
            $query->field('id,nickname,avator');
        }])->where(['follow_id' => $id, 'relation_type' => 1])->order('id desc')->paginate();
        LogService::record(
            user_id: getUid(),
            name: '查看粉丝',
            target_id: $id
        );
        return success($list);
    }
    // 关注用户
    public function doFollow($id)
    {
        $res = ModelFollow::toggleFollow($this->uid, $id);
        LogService::record(
            user_id: getUid(),
            name: '关注|取关用户',
            target_id: $id
        );
        if ($res) return success();
        return error();
    }
}
